//
//  TSRecordFilterView.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/7.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

protocol TSRecordFilterViewDelegate : NSObjectProtocol  {
    
    func completeFilterCondition(name:String, state:String, startDate:String, endDate:String)
    
    func completeFilter(status:UInt)
}

protocol TSDatePickerViewDelegate : NSObjectProtocol {
    func completeSelect(date:Date)
}

class TSRecordFilterView: UIView, TSDatePickerViewDelegate, UIGestureRecognizerDelegate {
    
    weak var delegate : TSRecordFilterViewDelegate?
    
    /** 是否是投注记录页 */
    var isInvestType : Bool = false {
        didSet {
            investContainer.isHidden = !isInvestType
            conversionContainer.isHidden = isInvestType
        }
    }
    
    var investContainer : UIView!        // 投注记录页container
    var conversionContainer : UIView!    // 账变明细container
    
    var nameTagView : TSTagView!
    var stateTagView : TSTagView!
    
    var startBtnPicker : UIButton!
    var endBtnPicker : UIButton!
    var datePickerView : TSDatePickerView!
    var currentClickBtn : UIButton!
    
    var collectionView : UICollectionView!
    var dataSource : Array<TSFilterItemModel> = []
    var clickItem : TSFilterItemModel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
//        let gesture = UITapGestureRecognizer.init(target: self, action: #selector(gestureAction(gesture:)))
//        gesture.delegate = self
//        self.addGestureRecognizer(gesture)
        configViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func gestureAction(gesture:UITapGestureRecognizer) {
        self.isHidden = true
    }
    
    func resetView() {
        
        let dateTuple = Date.getCurrentYearAndMonth()
        startBtnPicker.setTitle("\(dateTuple.0)-\(dateTuple.1)-1", for: .normal)
        endBtnPicker.setTitle(Date.currentTime(), for: .normal)
        
        nameTagView.resetTagView()
        stateTagView.resetTagView()
    }
    
    @objc func resetAction() {
        resetView()
        self.isHidden = true
    }
    
    @objc func sureAction() {
        if self.delegate != nil {
            
            if isInvestType {

                let startDate = startBtnPicker.currentTitle!+" 00:00:00"
                let endDate = endBtnPicker.currentTitle!+" 23:59:59"
                self.delegate?.completeFilterCondition(name: nameTagView.selectedItemTitle, state: stateTagView.selectedItemTitle, startDate: startDate, endDate: endDate)
            } else {
                self.delegate?.completeFilter(status: clickItem.status)
            }
        }
        self.isHidden = true
    }
    
    @objc func datePickerAction(sender:UIButton) {
        
        currentClickBtn = sender
        datePickerView.datePicker.date = Date.stringConvertDate(string: sender.currentTitle!)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3) {
            self.datePickerView.isHidden = false
        }
    }
    
    func completeSelect(date: Date) {
        
        if currentClickBtn == startBtnPicker {
            let result = Date.compareTimeOfSize(startDate: date, endDate: Date.stringConvertDate(string: endBtnPicker.currentTitle!))
            if !result {
                return
            }
        } else {
            let result = Date.compareTimeOfSize(startDate: Date.stringConvertDate(string: startBtnPicker.currentTitle!), endDate: date)
            if !result {
                return
            }
        }
                
        let dateFormatter : DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd"
        currentClickBtn.setTitle(dateFormatter.string(from: date), for: .normal)
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
            if touch.view == investContainer {
            return false
        }
        return true
    }
}

extension TSRecordFilterView : UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        clickItem = dataSource[indexPath.item]
        
        collectionView.reloadData()
    }
}

extension TSRecordFilterView : UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(TSFilterItemCollectionViewCell.self), for: indexPath) as? TSFilterItemCollectionViewCell
        
        let model = dataSource[indexPath.item]
        cell?.setupCell(model: dataSource[indexPath.item], isSelected: model.title == clickItem.title)
        
        return cell!
    }
        
}

extension TSRecordFilterView {
    
    func configViews() {
        
        createInverstFilterView()
        createConversionFilterView()
    }
    
    func createInverstFilterView() {
        
        investContainer = UIView.init()
        investContainer.backgroundColor = WHITE_COLOR
        addSubview(investContainer)
        investContainer.snp_makeConstraints { (make) in
            make.top.right.bottom.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.738)
        }
        
        let resetBtn = UIButton.init(type: .system)
        resetBtn.setTitle("取消", for: .normal)
        resetBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#282828"), for: .normal)
        resetBtn.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        resetBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        resetBtn.addTarget(self, action: #selector(resetAction), for: .touchUpInside)
        investContainer.addSubview(resetBtn)
        
        let sureBtn = UIButton.init(type: .system)
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(WHITE_COLOR, for: .normal)
        sureBtn.backgroundColor = BASE_PURPLE_COLOR
        sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        sureBtn.addTarget(self, action: #selector(sureAction), for: .touchUpInside)
        investContainer.addSubview(sureBtn)
        
        let bottomArea = STATUSBAR_HEIGHT > 20 ? 20 : 0
        let btnArray = [resetBtn, sureBtn]
        btnArray.snp.distributeViewsAlong(axisType: .horizontal, fixedSpacing: 0, leadSpacing: 0, tailSpacing: 0)
        btnArray.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().inset(bottomArea)
            make.height.equalTo(44)
        }
        
        let nameLabel = UILabel.init()
        nameLabel.text = "彩票名称"
        nameLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        nameLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        investContainer.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalTo(STATUSBAR_HEIGHT+15)
        }
        
        nameTagView = TSTagView.init()
        nameTagView.configTagView(itemsArray: ["幸运飞艇", "北京赛车"])
        nameTagView.backgroundColor = WHITE_COLOR
        investContainer.addSubview(nameTagView)
        nameTagView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(5)
            make.top.equalTo(nameLabel.snp_bottom).offset(15)
        }
        
        let stateLabel = UILabel.init()
        stateLabel.text = "彩票状态"
        stateLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        stateLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        investContainer.addSubview(stateLabel)
        stateLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(nameLabel)
            make.top.equalTo(nameTagView.snp_bottom).offset(18)
        }
        
        stateTagView = TSTagView.init()
        stateTagView.configTagView(itemsArray: ["所有状态", "已派奖", "未中奖","未中奖", "撤单"])
        stateTagView.backgroundColor = WHITE_COLOR
        investContainer.addSubview(stateTagView)
        stateTagView.snp.makeConstraints { (make) in
            make.left.right.equalTo(nameTagView)
            make.top.equalTo(stateLabel.snp_bottom).offset(15)
        }
        
        let dateLabel = UILabel.init()
        dateLabel.text = "选择时间段"
        dateLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        dateLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        investContainer.addSubview(dateLabel)
        dateLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(nameLabel)
            make.top.equalTo(stateTagView.snp_bottom).offset(18)
        }
        
        let regionLabel = UILabel.init()
        regionLabel.text = "到"
        regionLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        regionLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        investContainer.addSubview(regionLabel)
        regionLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(dateLabel.snp_bottom).offset(25)
        }
        
        let dateTuple = Date.getCurrentYearAndMonth()
        startBtnPicker = UIButton.init(type: .custom)
        startBtnPicker.tag = 1
        startBtnPicker.setTitle("\(dateTuple.0)-\(dateTuple.1)-1", for: .normal)
        startBtnPicker.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#282828"), for: .normal)
        startBtnPicker.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        startBtnPicker.addTarget(self, action: #selector(datePickerAction(sender:)), for: .touchUpInside)
        investContainer.addSubview(startBtnPicker)
        startBtnPicker.snp.makeConstraints { (make) in
            make.top.equalTo(regionLabel)
            make.left.equalTo(dateLabel)
            make.right.equalTo(regionLabel.snp_left).offset(-15)
            make.height.equalTo(13)
        }
        
        let line1 = UIView.init()
        line1.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#DDDDDD")
        investContainer.addSubview(line1)
        line1.snp.makeConstraints { (make) in
            make.bottom.equalTo(regionLabel).offset(3)
            make.left.right.equalTo(startBtnPicker).offset(2)
            make.height.equalTo(1)
        }
        
        endBtnPicker = UIButton.init(type: .custom)
        endBtnPicker.tag = 2
        endBtnPicker.setTitle(Date.currentTime(), for: .normal)
        endBtnPicker.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#282828"), for: .normal)
        endBtnPicker.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        endBtnPicker.addTarget(self, action: #selector(datePickerAction(sender:)), for: .touchUpInside)
        investContainer.addSubview(endBtnPicker)
        endBtnPicker.snp.makeConstraints { (make) in
            make.top.equalTo(regionLabel)
            make.left.equalTo(regionLabel.snp_right).offset(15)
            make.right.equalToSuperview().inset(15)
            make.height.equalTo(13)
        }
        
        let line2 = UIView.init()
        line2.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#DDDDDD")
        investContainer.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.bottom.equalTo(line1)
            make.left.right.equalTo(endBtnPicker).offset(2)
            make.height.equalTo(line1)
        }
        
        datePickerView = TSDatePickerView.init()
        datePickerView.isHidden = true
        datePickerView.delegate = self
        addSubview(datePickerView)
        datePickerView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            if STATUSBAR_HEIGHT > 20 {
                make.height.equalTo(235+20)
            } else {
                make.height.equalTo(235)
            }
        }
    }

    func createConversionFilterView() {
        
        let titleArray = ["所有账变", "充值到中心钱包", "中心钱包转金币", "金币购彩", "撤单回款", "中奖盈利", "下级收益", "金币转中心", "USDT中心钱包提现", "人民币中心钱包提现", "USDT盈利钱包提现", "人民币盈利钱包提现", "USDT收益提现", "人民币收益提现", "盈利转中心"]
        let codeArray = [0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 30]
        
        for index in 0..<titleArray.count {
            let model = TSFilterItemModel.init(title: titleArray[index], status: UInt(codeArray[index]))
            if index == 0 {
                clickItem = model
            }
            dataSource.append(model)
        }
        
        conversionContainer = UIView.init()
        conversionContainer.backgroundColor = WHITE_COLOR
        addSubview(conversionContainer)
        conversionContainer.snp_makeConstraints { (make) in
            make.top.right.bottom.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.738)
        }
        
        let resetBtn = UIButton.init(type: .system)
        resetBtn.setTitle("取消", for: .normal)
        resetBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#282828"), for: .normal)
        resetBtn.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        resetBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        resetBtn.addTarget(self, action: #selector(resetAction), for: .touchUpInside)
        conversionContainer.addSubview(resetBtn)
        
        let sureBtn = UIButton.init(type: .system)
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(WHITE_COLOR, for: .normal)
        sureBtn.backgroundColor = BASE_PURPLE_COLOR
        sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        sureBtn.addTarget(self, action: #selector(sureAction), for: .touchUpInside)
        conversionContainer.addSubview(sureBtn)
        
        let bottomArea = STATUSBAR_HEIGHT > 20 ? 20 : 0
        let btnArray = [resetBtn, sureBtn]
        btnArray.snp.distributeViewsAlong(axisType: .horizontal, fixedSpacing: 0, leadSpacing: 0, tailSpacing: 0)
        btnArray.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().inset(bottomArea)
            make.height.equalTo(44)
        }
                
        let nameLabel = UILabel.init()
        nameLabel.text = "账变类型"
        nameLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        nameLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        conversionContainer.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalTo(STATUSBAR_HEIGHT+15)
        }
        
        let collectionW = CGFloat(SCREEN_WIDTH * 0.738 - 2*15)
        let lineSpacing : CGFloat = 10
        let itemW = (collectionW - 10) * 0.5
        let itemH : CGFloat = 22
        
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = CGSize(width: itemW, height: itemH)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = lineSpacing
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = WHITE_COLOR
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.bounces = false
        collectionView.register(TSFilterItemCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(TSFilterItemCollectionViewCell.self))
        conversionContainer.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.top.equalTo(nameLabel.snp_bottom).offset(15)
            make.size.equalTo(CGSize(width: collectionW, height: itemH*8 + lineSpacing*7))
        }
    }
}

//MARK: - TSDatePickerView
class TSDatePickerView: UIView {
    
    weak var delegate : TSDatePickerViewDelegate?
    var datePicker: UIDatePicker!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = WHITE_COLOR
        configViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func cacncelAction() {
        self.isHidden = true
    }
    
    @objc func sureAction() {
        
        self.cacncelAction()
        
        let theDate : Date = self.datePicker.date
//        let desc = theDate.description(with: Locale.current)
//        NSLog("the date formate is %@ ", desc)
        
        let dateFormatter : DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd"
        NSLog("the date formate is: %@", dateFormatter.string(from: theDate))
        
        if self.delegate != nil {
            self.delegate?.completeSelect(date: theDate)
        }
    }
    
    func configViews() {
        
        let investContainer = UIView.init()
        investContainer.backgroundColor = WHITE_COLOR
        addSubview(investContainer)
        investContainer.snp_makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(35)
        }
        
        let cancelBtn = UIButton.init(type: .system)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.setTitleColor(BASE_PURPLE_COLOR, for: .normal)
        cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        cancelBtn.addTarget(self, action: #selector(cacncelAction), for: .touchUpInside)
        investContainer.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(15)
        }
        
        let sureBtn = UIButton.init(type: .system)
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(BASE_PURPLE_COLOR, for: .normal)
        sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        sureBtn.addTarget(self, action: #selector(sureAction), for: .touchUpInside)
        investContainer.addSubview(sureBtn)
        sureBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().inset(15)
        }
        
        datePicker = UIDatePicker()
        datePicker.maximumDate = Date()
        datePicker.locale = NSLocale(localeIdentifier: "zh-Hans") as Locale
        datePicker.datePickerMode = .date
        addSubview(datePicker)
        datePicker.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(200)
            if STATUSBAR_HEIGHT > 20 {
                make.bottom.equalToSuperview().inset(20)
            } else {
                make.bottom.equalToSuperview()
            }
        }
    }
}
